#!/usr/bin/env ruby
require "ftools"

class HappyCoder

  public
  def install
    if is_installed?
      puts "Happy Coder ya esta instalado :)"
    else
      copy_files
      clear_caches
      display_end_notes
    end
  end


  private
  def copy_files
    puts "Instalando Happy Coder en #{dest}"
    %x(rm "#{dest}/Happy Coder.icns") if File.exists? "#{dest}/Happy Coder.icns"
    %x(cp "#{orig}/Happy Coder.icns" "#{dest}")
    %x(rm "#{dest}/Happy Coder.keylayout")  if File.exists? "#{dest}/Happy Coder.keylayout"
    %x(cp "#{orig}/Happy Coder.keylayout" "#{dest}")
  end

  def is_installed?
    if File.exists?(dest + "/Happy Coder.keylayout")
      if File.compare(dest + "/Happy Coder.keylayout",orig + "/Happy Coder.keylayout")
        return true
      end
    else
      return false
    end
  end

  def orig
    if __FILE__.match(/Resources/)
      File.dirname(__FILE__)
    else
      File.dirname(__FILE__) + "/.."
    end
  end

  def dest
    ENV['HOME'] + "/Library/Keyboard Layouts/"
  end

  def clear_caches
    uid = %x(id $username -u)
    puts %x(rm /Library/Caches/com.apple.IntlDataCache.le.#{uid})
    puts %x(rm /Library/Caches/com.apple.IntlDataCache.le.kbdx.#{uid})
    puts %x(rm /Library/Caches/com.apple.IntlDataCache.le.sbdl.#{uid})
  end

  def display_end_notes
    %x(osascript #{orig}/open_system_prefs.applescript)
    puts "Instalacion completada! :)"
  end

end

HappyCoder.new.install